package com.agileai.portal.controller.wcm;

import java.util.ArrayList;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageListHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.portal.bizmoduler.wcm.InfomationManage.AuthType;
import com.agileai.portal.filter.UserCacheManager;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class InfomationManageListHandler
        extends TreeAndContentManageListHandler {
	public static final String LastEditTypeSessionKey = "_lastEditType_";
	
	public InfomationManageListHandler() {
        super();
        this.serviceId = buildServiceId(InfomationManage.class);
        this.rootColumnId = "00000000-0000-0000-00000000000000000";
        this.defaultTabId = "WcmInfomation";
        this.columnIdField = "COL_ID";
        this.columnNameField = "COL_NAME";
        this.columnParentIdField = "COL_PID";
        this.columnSortField = "COL_ORDERNO";
    }
    
	public ViewRenderer prepareDisplay(DataParam param){
		User user = (User) this.getUser();
		String columnId = param.get("columnId",this.rootColumnId);
		if (columnId.equals(this.rootColumnId)){
			 initParamItem(param,"showChildNodeRecords",param.get("showChildNodeRecords", "Y"));
		}
		initParameters(param);
		this.setAttributes(param);

		this.setAttribute("columnId", columnId);
		this.setAttribute("isRootColumnId",String.valueOf(this.rootColumnId.equals(columnId)));
		
		TreeBuilder treeBuilder = provideTreeBuilder(param);
		TreeModel treeModel = treeBuilder.buildTreeModel();
		TreeModel filterTreeModel = null;
		TreeModel childModel = treeModel.getFullTreeMap().get(columnId);
		if (childModel != null){
			filterTreeModel = childModel;
		}else{
			filterTreeModel = treeModel;
		}
		
		String menuTreeSyntax = this.getTreeSyntax(treeModel,new StringBuffer());
		this.setAttribute("menuTreeSyntax", menuTreeSyntax);
		String tabId = param.get(TreeAndContentManage.TAB_ID,this.defaultTabId);
		
		if (!TreeAndContentManage.BASE_TAB_ID.equals(tabId)){
			param.put("columnId",columnId);
			List<DataRow> rsList = getService().findContentRecords(filterTreeModel,tabId,param);
			this.setRsList(rsList);			
		}else{
			DataParam queryParam = new DataParam(columnIdField,columnId);
			DataRow row = getService().queryTreeRecord(queryParam);
			this.setAttributes(row);
		}
		
		String userCode = user.getUserCode();
		this.setAttribute("userCode", userCode);
		
		this.setAttribute(TreeAndContentManage.TAB_ID, tabId);
		this.setAttribute(TreeAndContentManage.TAB_INDEX, getTabIndex(tabId));
		
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
    protected void processPageAttributes(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("WcmInfomation".equals(tabId)) {
            setAttribute("infoAuthType",
                         FormSelectFactory.create("WCM_AUTH_TYPE")
                                          .addSelectedValue(param.get("infoAuthType")));
            setAttribute("infoState",
                         FormSelectFactory.create("WCM_INFO_STATE")
                                          .addSelectedValue(param.get("infoState")));
            setAttribute("infoSetTop",
                         FormSelectFactory.create("BOOL_DEFINE")
                                          .addSelectedValue(param.get("infoSetTop")));
            setAttribute("supportComment",
                         FormSelectFactory.create("BOOL_DEFINE")
                                          .addSelectedValue(param.get("supportComment")));
            setAttribute("commentAnonymous",
                         FormSelectFactory.create("BOOL_DEFINE")
                                          .addSelectedValue(param.get("commentAnonymous")));
            
            initMappingItem("INFO_AUTH_TYPE",
                            FormSelectFactory.create("WCM_AUTH_TYPE")
                                             .getContent());
            initMappingItem("INFO_STATE",
                            FormSelectFactory.create("WCM_INFO_STATE")
                                             .getContent());
            initMappingItem("INFO_SETTOP",
                            FormSelectFactory.create("BOOL_DEFINE").getContent());
            initMappingItem("INFO_SUPPORT_COMMENT",
                            FormSelectFactory.create("BOOL_DEFINE").getContent());
        }
        String editMode = param.get("editMode"); 
        this.setAttribute("editMode",editMode); 
    }

    protected void initParameters(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);
        if ("WcmInfomation".equals(tabId)) {
            initParamItem(param, "infoAuthType", "");
            initParamItem(param, "infoState", "");
            initParamItem(param, "startCreateTime", "");
            initParamItem(param, "endCreateTime", "");
            initParamItem(param, "startPublishTime", "");
            initParamItem(param, "endPublishTime", "");
            initParamItem(param, "infoSetTop", "");
            initParamItem(param, "supportComment", "");
            initParamItem(param, "commentAnonymous", "");
            initParamItem(param, "minReadCount", "");
            initParamItem(param, "maxReadCount", "");
            initParamItem(param, "infoTitle", "");
            initParamItem(param, "infoCreater", "");
            initParamItem(param, "infoPublisher", "");
        }
    }
    
    @PageAction
    public ViewRenderer retrieveLastEditType(DataParam param){
    	String lastEditType = (String)this.getSessionAttribute(LastEditTypeSessionKey);
    	if (StringUtil.isNullOrEmpty(lastEditType)){
    		lastEditType = InfomationManage.EditType.Profile;
    	}
    	return new AjaxRenderer(lastEditType);
    }
    
    protected TreeBuilder provideTreeBuilder(DataParam param) {
        InfomationManage service = this.getService();
        List<DataRow> menuRecords = service.findTreeRecords(new DataParam());
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords,
                                                  this.columnIdField,
                                                  this.columnNameField,
                                                  this.columnParentIdField);
        return treeBuilder;
    }
    
	
	protected void buildTreeSyntax(StringBuffer treeSyntax,TreeModel treeModel){
		List<TreeModel> children = treeModel.getChildren();
		String parentId = treeModel.getId();
		User user = (User)this.getUser();
        for (int i=0;i < children.size();i++){
        	TreeModel child = children.get(i);
            String curNodeId = child.getId();
            if (user.containResouce(Resource.Type.InfoColumn, curNodeId)
            		|| "user".equals(user.getUserCode()) || "admin".equals(user.getUserCode())){
                String curNodeName = child.getName();
                if (!ListUtil.isNullOrEmpty(child.getChildren())){
                	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:refreshContent('"+curNodeId+"')\");");
                	treeSyntax.append("\r\n");
                }else{
                	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:refreshContent('"+curNodeId+"')\");");
                	treeSyntax.append("\r\n");
                }
                this.buildTreeSyntax(treeSyntax,child);            	
            }
        }
    }	
    
    @PageAction
    public ViewRenderer modifyInfomationState(DataParam param){
    	String responseText = FAIL;
    	String infomationId = param.get("INFO_ID");
    	String bizActionType = param.get("bizActionType");
    	InfomationManage infomationManage = this.getService();
    	User user = (User)this.getUser();
    	infomationManage.modifyInfomationState(infomationId, bizActionType,user);

    	DataRow row = infomationManage.getContentRecord(infomationId);
    	if (AuthType.Private.equalsIgnoreCase(row.getString("INFO_AUTH_TYPE"))
    			&& InfomationManage.BizActionType.Approve.equals(bizActionType)){
    		UserCacheManager.getOnly().truncateUsers();
    	}
    	responseText = SUCCESS;
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer modifyInfomationStates(DataParam param){
    	String responseText = FAIL;
    	String infoIds = param.get("infoIds");
    	String bizActionType = param.get("bizActionType");
    	InfomationManage infomationManage = this.getService();
    	User user = (User)this.getUser();
    	int index = 0;
    	if(!"".equals(infoIds)){
    		 String[] idArray = infoIds.split(",");
			 for(int i=0;i < idArray.length;i++ ){
				 String infomationId = idArray[i];
				 DataRow row = infomationManage.getCurrentInfoRecord(infomationId);
				 String infoState = row.getString("INFO_STATE");
				 if("submit".equals(bizActionType) && "draft".equals(infoState) || "unsubmit".equals(bizActionType) && "waitepublish".equals(infoState)
						  || "approve".equals(bizActionType) && "waitepublish".equals(infoState) || "unapprove".equals(bizActionType) && "published".equals(infoState)){
					 index = index + 0;
				 }else{
					 index = index +1;
				 }
			 }
    	}
    	
    	if(index == 0){
    		if(!"".equals(infoIds)){
       		 	String[] idArray = infoIds.split(",");
    			for(int i=0;i < idArray.length;i++ ){
    				String infomationId = idArray[i];
    				DataRow row = infomationManage.getCurrentInfoRecord(infomationId);
    				String infoState = row.getString("INFO_STATE");
    				
					if("submit".equals(bizActionType) && "draft".equals(infoState) ){
						infomationManage.modifyInfomationState(infomationId, bizActionType,user); 
					}else if("unsubmit".equals(bizActionType) && "waitepublish".equals(infoState)){
						infomationManage.modifyInfomationState(infomationId, bizActionType,user);
					}else if("approve".equals(bizActionType) && "waitepublish".equals(infoState)){
						infomationManage.modifyInfomationState(infomationId, bizActionType,user);
					}else if("unapprove".equals(bizActionType) && "published".equals(infoState)){
						infomationManage.modifyInfomationState(infomationId, bizActionType,user);
					} 
    			 }
        	}
    	}else{
			return new AjaxRenderer(responseText);
		}
    	
    	List<DataRow> list = infomationManage.getContentRecords(infoIds);
    	for(int i=0;i < list.size();i++){
    		DataRow row = list.get(i);
    		if (AuthType.Private.equalsIgnoreCase(row.getString("INFO_AUTH_TYPE"))
        			&& InfomationManage.BizActionType.Approve.equals(bizActionType)){
        		UserCacheManager.getOnly().truncateUsers();
        		break;
        	}
    	}
    	responseText = SUCCESS;
    	return new AjaxRenderer(responseText);
    }
    
	@PageAction
	public ViewRenderer isExistRelation(DataParam param){
		String responseText = "N";
		String columnId = param.get("infoId");
		String resourceId = columnId;
		String resourceType = Resource.Type.Infomation;
		boolean isExistSecurityRelation = isExistSecurityRelation(resourceId, resourceType);
		if (isExistSecurityRelation){
			return new AjaxRenderer("Y");
		}
		return new AjaxRenderer(responseText);
	}
	private boolean isExistSecurityRelation(String resourceId,String resourceType){
		boolean result = false;
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		List<DataRow> roleList = authorizationConfig.retrieveRoleList(resourceType, resourceId);
		if (roleList != null && roleList.size() > 0){
			result = true;
		}
		List<DataRow> userList = authorizationConfig.retrieveUserList(resourceType, resourceId);
		if (userList != null && userList.size() > 0){
			result = true;
		}
		List<DataRow> groupList = authorizationConfig.retrieveGroupList(resourceType, resourceId);
		if (groupList != null && groupList.size() > 0){
			result = true;
		}
		return result;
	}	    
    
    protected List<String> getTabList() {
        List<String> result = new ArrayList<String>();
        result.add("WcmInfomation");
        return result;
    }

    protected InfomationManage getService() {
        return (InfomationManage) this.lookupService(this.getServiceId());
    }
}
